package com.wdz.pma.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

//    1.内存中的身份验证：（定义用户名、密码、角色名字）
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled " + "FROM user_accounts WHERE username = ?")
//                提供【用户名】的查询语句
                .authoritiesByUsernameQuery("SELECT username, role " + "FROM user_accounts WHERE username = ?")
//                提供【角色权限】的查询语句
                .passwordEncoder(bCryptPasswordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers("/projects/new").hasRole("ADMIN")//     1.访问【项目创建页面】路径（/projects/new）需要【ADMIN】
//                .antMatchers("/projects/save").hasRole("ADMIN")
//                .antMatchers("/students/new").hasRole("ADMIN")
//                .antMatchers("/students/save").hasRole("ADMIN")

                .antMatchers("/", "/**").permitAll()//  不能放在最上面，否则下面的规则不生效
                .and()
                .formLogin();
//    【.formLogin()】:使用默认的表单登陆验证;【.loginPage()：指定登陆页面的路径】

    }

}
